<script setup lang="ts">
import XtxSwiper from '@/components/XtxSwiper.vue';
import CustomNavbar from './components/CustomNavbar.vue';
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import type { BannerItem, CategoryItem, HotItem } from '@/types/home';
import CategoryPanel from './components/CategoryPanel.vue';
import HotPanel from './components/HotPanel.vue';
import XtxGuess from '@/components/XtxGuess.vue';
import PageSkeleton from './components/PageSkeleton.vue';
import { useGuessList } from '@/composables';

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  await getHomeBannerAPI().then(res => {
    bannerList.value = res.result
  })
}
// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  await getHomeCategoryAPI().then(res => {
    categoryList.value = res.result
  })
}
// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  await getHomeHotAPI().then(res => {
    hotList.value = res.result
  })
}

// 是否加载标记
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData()
  ])
  isLoading.value = false
})
// 获取猜你喜欢组件实例
// const guessRef = ref<XtxGuessInstance>()
// 滚动触底
// const onScrolltolower = () => {
//   guessRef.value?.getMore()
// }
const { guessRef, onScrolltolower } = useGuessList()

const isTriggered = ref(false)
// 下拉刷新事件
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore()
  ])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered" @scrolltolower="onScrolltolower" class="scroll-view" scroll-y>
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading"/>
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList"/>
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList"/>
      <!-- 热门推荐 -->
      <HotPanel :list="hotList"/>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"/>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1
}
</style>
